from ..db import db
from typing import Tuple, Any
from sqlalchemy import Integer, Column, Table, DateTime
from datetime import datetime
from sqlalchemy.sql import ColumnCollection, ColumnElement
from sqlalchemy.orm import Query
import json
from ..util import SerializableDBType


class BaseModel:
    __table__: Table
    __tablename__: str
    query: Query

    @staticmethod
    def _datetime_to_str(dt: datetime) -> str:
        if dt is not None:
            return dt.strftime("%Y-%m-%d %H:%M:%S.%f")
        else:
            return ""

    def __repr__(self) -> str:
        return self.to_json()

    def to_json(self) -> str:
        return json.dumps(self.to_serealized_dict())

    def to_serealized_dict(self) -> dict[str, SerializableDBType]:
        d = {}
        for col in self.__table__.columns:
            col: ColumnElement
            d[col.name] = getattr(self, col.name)
            if isinstance(col.type, DateTime):
                d[col.name] = self._datetime_to_str(d[col.name])
        return d

    def to_dict(self) -> dict:
        '''auto to dict'''
        return {key: getattr(self, key) for key in self.__table__.columns.keys()}

    def save(self) -> bool:
        '''save current model instance to db, return is_successful'''
        try:
            db.session.add(self)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print('[数据保存时发生错误]', e)
            raise e

    def delete(self) -> bool:
        '''delete current model instance in db, return is_successful'''
        try:
            db.session.delete(self)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print('[数据删除时发生错误]', e)
